<template>
  <el-breadcrumb>
    <el-breadcrumb-item>公众监督数据管理</el-breadcrumb-item>
    <el-breadcrumb-item>指派网格员</el-breadcrumb-item>
  </el-breadcrumb>

  <DataDetails />

  <div class="assign">
    <el-form inline size="small">
      <el-form-item label="是否异地指派">
        <el-switch v-model="isRemote" size="small" />
      </el-form-item>
    </el-form>

    <!-- 本地指派 -->
    <el-form inline v-if="!isRemote" size="small">
      <el-form-item label="指派给">
        <el-select v-model="gmIdLocal" placeholder="请选择本地网格员" style="width: 200px;">
          <el-option
            v-for="m in gridMemberLocalArr"
            :key="m.gmId"
            :label="m.gmName"
            :value="m.gmId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-popconfirm title="确定要指派吗?" @confirm="assignEvent">
          <template #reference>
            <el-button type="primary">本地指派</el-button>
          </template>
        </el-popconfirm>
      </el-form-item>
    </el-form>

    <!-- 异地指派 -->
    <el-form inline v-if="isRemote" size="small">
      <el-form-item label="省区域">
        <el-select v-model="provinceIdNoLocal" @change="changeProvince" placeholder="请选择省" style="width: 200px;">
          <el-option
            v-for="p in provinceArr"
            :key="p.provinceId"
            :label="p.provinceName"
            :value="p.provinceId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="市区域">
        <el-select v-model="cityIdNoLocal" @change="changeCity" placeholder="请选择市" style="width: 200px;">
          <el-option
            v-for="c in cityArr"
            :key="c.cityId"
            :label="c.cityName"
            :value="c.cityId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="异地指派给">
        <el-select v-model="gmIdNoLocal" placeholder="请选择网格员" style="width: 200px;">
          <el-option
            v-for="m in gridMemberNoLocalArr"
            :key="m.gmId"
            :label="m.gmName"
            :value="m.gmId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-popconfirm title="确定要指派吗?" @confirm="assignEvent">
          <template #reference>
            <el-button type="primary">异地指派</el-button>
          </template>
        </el-popconfirm>
      </el-form-item>
    </el-form>
  </div>
</template>


<script setup>
import DataDetails from "../../components/DataDetails.vue";
import { ref, inject, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { getCurDate, getCurTime } from "../../common.js";

const axios = inject("axios");
const myElMessage = inject("myElMessage");
const router = useRouter();
const route = useRoute();

const isRemote = ref(false);
const gmIdLocal = ref("");            // 初始化为空字符串
const gridMemberLocalArr = ref([]);
const gmIdNoLocal = ref("");
const gridMemberNoLocalArr = ref([]);
const provinceArr = ref([]);
const cityArr = ref([]);
const provinceIdNoLocal = ref("");
const cityIdNoLocal = ref("");

const init = async () => {
  try {
    // 本地网格员
    const localRes = await axios.get("gridMember/listGridMemberByProvinceId", {
      params: {
        provinceId: route.query.provinceId,
        cityId: route.query.cityId,
        state: 0
      }
    });
    if (localRes.data.code === 6000 && Array.isArray(localRes.data.t) && localRes.data.t.length > 0) {
      gridMemberLocalArr.value = localRes.data.t.map(m => ({
        ...m,
        gmId: String(m.gmId)  // 转为字符串
      }));
      gmIdLocal.value = gridMemberLocalArr.value[0].gmId;
    } else {
      gridMemberLocalArr.value = [];
      gmIdLocal.value = "";
    }

    // 省份列表
    const provinceRes = await axios.get("gridProvince/listGridProvinceAll");
    if (Array.isArray(provinceRes.data) && provinceRes.data.length > 0) {
      provinceArr.value = provinceRes.data.map(p => ({
        ...p,
        provinceId: String(p.provinceId)
      }));
      provinceIdNoLocal.value = provinceArr.value[0].provinceId;
      await changeProvince();
    } else {
      console.error("省接口异常:", provinceRes.data);
    }
  } catch (error) {
    console.error("初始化异常:", error);
  }
};

const changeProvince = async () => {
  try {
    const cityRes = await axios.get("gridCity/listGridCityByProvinceId", {
      params: { provinceId: provinceIdNoLocal.value }
    });
    if (Array.isArray(cityRes.data) && cityRes.data.length > 0) {
      cityArr.value = cityRes.data.map(c => ({
        ...c,
        cityId: String(c.cityId)
      }));
      cityIdNoLocal.value = cityArr.value[0].cityId;
      await changeCity();
    } else {
      cityArr.value = [];
      cityIdNoLocal.value = "";
      gridMemberNoLocalArr.value = [];
      gmIdNoLocal.value = "";
    }
  } catch (error) {
    console.error("changeProvince异常:", error);
  }
};

const changeCity = async () => {
  try {
    const memberRes = await axios.get("gridMember/listGridMemberByProvinceId", {
      params: {
        provinceId: provinceIdNoLocal.value,
        cityId: cityIdNoLocal.value,
        state: 0
      }
    });
    if (memberRes.data.code === 6000 && Array.isArray(memberRes.data.t) && memberRes.data.t.length > 0) {
      gridMemberNoLocalArr.value = memberRes.data.t.map(m => ({
        ...m,
        gmId: String(m.gmId)
      }));
      gmIdNoLocal.value = gridMemberNoLocalArr.value[0].gmId;
    } else {
      gridMemberNoLocalArr.value = [];
      gmIdNoLocal.value = "";
    }
  } catch (error) {
    console.error("changeCity异常:", error);
  }
};

const assignEvent = () => {
  const gmId = isRemote.value ? gmIdNoLocal.value : gmIdLocal.value;
  const afId = route.query.afId;
  if (!gmId) return myElMessage('请选择一个网格员！', 'warning');
  axios.post("aqiFeedback/updateAqiFeedbackAssign", {
    gmId,
    assignDate: getCurDate(),
    assignTime: getCurTime(),
    state: 1,
    afId
  }).then(res => {
    if (res.data === 1 || (res.data.code && res.data.code === 6000)) {
      myElMessage('指派成功！', 'success');
      router.push('/index/feedbackList');
    } else {
      myElMessage('指派失败！', 'error');
    }
  }).catch(error => {
    console.error("指派失败:", error);
    myElMessage('服务器异常，请稍后重试。', 'error');
  });
};

onMounted(() => {
  init();
});
</script>


<style scoped>
.assign {
  margin-top: 20px;
  display: flex;
  align-items: center;
}
</style>